<template>
  <div class="app-container" v-loading="loading">
    <div class="cardInfo">
      <div style="display: flex">
        <div :class="fontImg ? 'cardImg' : 'cardImgx'" v-for="(item, index) in imgList" :key="index">
          <img :src="item" :alt="item" class="mpImg" @click="bindImg(index)" />
        </div>
      </div>
      <div class="info">
        <div class="cardInfoItem" v-for="(item, index) in carInfoList" :key="index">
          <div v-for="(listText, index) in item.list" :key="index">{{ listText.text }}</div>
        </div>
      </div>
    </div>
    <el-form :model="userInfo" :rules="userRules" ref="userInfo" label-width="150px">
      <div class="dis">
        <div style="width: 30%;margin-right:100px">
          <el-form-item label="更换名片图" style="margin-top: 20px">
            <el-upload
              :class="{ hide: isHideUploadEdit }"
              ref="uploadAvatar"
              list-type="picture-card"
              :action="uploadBaseUrl"
              :data="{ filetype: '更换名片图', app: 'shulan', module: '2', sourceKey: '1' }"
              :limit="2"
              :before-upload="onUploadBefore"
              :on-success="onUploadSuccess"
              :on-error="onUploadError"
              :on-exceed="onUploadExceed"
              :on-remove="onUploadRemove"
              accept=".jpg,.jpeg,.png"
              :multiple="true"
              :file-list="avatarPreviewList"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="合作业务手机号" :prop="this.userInfo.istg == '2' ? '' : 'mobile'">
            <el-input v-model.number="userInfo.mobile" clearable></el-input>
          </el-form-item>
          <el-form-item label="城市" :prop="this.userInfo.istg == '2' ? '' : 'city'">
            <el-select v-model="userInfo.city" filterable placeholder="请选择" clearable style="width: 100%">
              <el-option
                v-for="item in cityOptions"
                :key="item.code"
                :label="item.city"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="认证来源" :prop="this.userInfo.istg == '2' ? '' : 'authSource'">
            <el-select
              v-model="authSourceName"
              placeholder="请选择"
              clearable
              @change="handleChangeAuthSource"
              style="width: 100%"
            >
              <el-option
                v-for="item in authSourceList"
                :key="item.id"
                :label="item.label"
                :value="item.userName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="提交认证时间">
            <span>{{ authenticationTime }}</span>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="经纪人姓名" :prop="this.userInfo.istg == '2' ? '' : 'realName'">
            <el-input v-model="userInfo.realName"></el-input>
          </el-form-item>
          <el-form-item label="品牌" :prop="this.userInfo.istg == '2' ? '' : 'shopShortName'">
            <el-select
              v-model="userInfo.shopShortName"
              filterable
              remote
              placeholder="请输入关键词"
              :remote-method="remoteShopHandler"
              @change="handleChangeShop"
              style="width: 100%"
            >
              <el-option
                v-for="item in shopOptions"
                :key="item.shopId"
                :label="item.shopShortName"
                :value="item.shopId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="门店" :prop="this.userInfo.istg == '2' ? '' : 'storeName'">
            <el-select
              v-model="userInfo.storeName"
              filterable
              remote
              placeholder="请输入关键词"
              :remote-method="remoteStoreHandler"
              @change="handleChangeStore"
            >
              <el-option v-for="item in storeOptions" :key="item.storeId" :label="item.storeName" :value="item.storeId">
                <div style="float: left">{{ item.storeName }}</div>
                <div style="float: right; color: #8492a6; font-size: 13px">{{ item.storeAddr }}</div>
              </el-option>
            </el-select>
            <span v-hasPermi="['reviewActivities:memberManage:manual']" style="margin-left: 10px">
              没有想搜的门店，
              <span style="color: red; cursor: pointer" @click="showPop">手工创建</span>
            </span>
          </el-form-item>
          <el-form-item label="门店地址" :prop="this.userInfo.istg == '2' ? '' : 'storeAddr'">
            <el-input v-model.number="userInfo.storeAddr"></el-input>
          </el-form-item>
          <el-form-item label="审核结论" prop="istg">
            <el-button
              size="mini"
              v-model="userInfo.istg"
              @click="failedAudit('true')"
              :type="this.userInfo.istg === '1' ? 'primary' : ''"
            >
              认证通过
            </el-button>
            <el-button
              size="mini"
              v-model="userInfo.istg"
              @click="failedAudit('false')"
              :type="this.userInfo.istg === '2' ? 'primary' : ''"
            >
              认证不通过
            </el-button>
          </el-form-item>
          <el-form-item label="未通过原因" v-if="isfailedAudit" prop="noPassReason">
            <template>
              <div>
                <el-select
                  v-model="selectValue"
                  placeholder="请选择"
                  @change="handleChangeSelectValue"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in setPassReason"
                    :key="item.key"
                    :label="item.label"
                    :value="item.key"
                  ></el-option>
                </el-select>
                <div style="margin-top: 15px">
                  <el-input
                    type="textarea"
                    placeholder="请输入未通过原因"
                    v-model="userInfo.noPassReason"
                    maxlength="50"
                    :rows="4"
                    show-word-limit
                  ></el-input>
                </div>
              </div>
            </template>
          </el-form-item>
        </div>
      </div>
      <div style="margin:30px 0 0 350px">
        <el-form-item v-if="authentType == 3">
          <el-button @click="cancelBut">取消认证</el-button>
          <el-button type="primary" @click="saveConfirm('userInfo')" :disabled="!submitAble" :loading=loadingBut>保存并更新认证</el-button>
        </el-form-item>
        <el-form-item v-else-if="authentType == 4">
          <el-button type="primary" @click="saveConfirm('userInfo')" :disabled="!submitAble" :loading=loadingBut>保存并更新认证</el-button>
        </el-form-item>
        <el-form-item v-else>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm('userInfo')" :disabled="!submitAble" :loading=loadingBut>提交</el-button>
        </el-form-item>
      </div>
    </el-form>

    <!-- 手工创建门店弹层 -->
    <el-dialog
      width="600px"
      title="门店新建"
      :visible.sync="createShopVisible"
      :close-on-click-modal="false"
      append-to-body
    >
      <create-shop-pop @onclose="createShopVisible = false" @oncreateshop="handleCreateShop"></create-shop-pop>
    </el-dialog>
  </div>
</template>
<script>
import {
  searchStore,
  userVerified,
  searchShop,
  searchSaleName,
  onlineauthentication,
} from "@/api/reviewActivities/memberManage";
import CITYS from "@/utils/config/citys";
import CreateShopPop from "./com/create-shop-pop";

export default {
  components: {
    CreateShopPop,
  },
  data() {
    //合作业务手机号正则判断
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入合作业务手机号"));
      } else {
        if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error("合作业务手机号格式不正确"));
        } else {
          callback();
        }
      }
    };
    this.uploadBaseUrl = `https://${
      location.hostname === "mgr.shulanfd.com" ? "api" : "api-dev"
    }.shulanfd.com/aist-filesvr-web/api/files`;
    return {
      loading: false,
      loadingBut:false, //提交按钮的loading
      cityOptions: [],
      storeOptions: [],
      shopOptions: [],
      saleUserOptions: [],
      setPassReason: [],
      authSourceList: [],
      selectValue: "",
      selectValueTmp: [], //缓存数据
      authSourceName: "",
      userInfo: {
        city: "", // 城市
        realName: "", // 真实姓名
        mobile: "", //合作业务手机号
        storeId: "", // 门店id
        storeName: "", // 门店
        storeAddr: "", // 门店地址
        shopId: "", //品牌id
        shopShortName: "", //品牌名称
        userId: "", //用户id
        newAddFileId: [], //更换名片
        noPassReason: "", //未通过原因
        onlineOffline: 1, //线上/线下审核 1:线上  2:线下
        istg: "1",
        saleUserId: "", //认证来源id
        authSource: "", //认证来源
        noPassReasonKey: "", //未通过原因的key
      },
      userRules: {
        realName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        mobile: [{ required: true, validator: validatePass, trigger: "blur" }],
        storeAddr: [{ required: true, message: "门店地址不能为空", trigger: "blur" }],
        istg: [{ required: true, message: "审核结论不能为空", trigger: "blur" }],
        noPassReason: [{ required: true, message: "未通过原因不能为空", trigger: "blur" }],
        shopShortName: [{ required: true, message: "品牌不能为空", trigger: "blur" }],
        storeName: [{ required: true, message: "门店不能为空", trigger: "blur" }],
        city: [{ required: true, message: "城市不能为空", trigger: "blur" }],
        authSource: [{ required: true, message: "认证来源不能为空", trigger: "blur" }],
      },
      imgList: [],
      carInfoList: [],
      avatarPreviewList: [],
      authenticationTime: "", //认证时间
      createShopVisible: false, //手工创建
      isHideUploadEdit: false, // 更换名片图
      isfailedAudit: false, //审核未通过
      istg: "", //审核是否通过
      authentType: this.$route.query.type, //用来判断查看认证还是填写认证

      fontImg: true, //放大图片
    };
  },
  created() {
    this.cityOptions = CITYS.map((item) => {
      return { ...item, value: item.city.replace("市", "") };
    });
    for (var i in this.cityOptions) {
      if (this.cityOptions[i].city === "上海市") {
        this.userInfo.city = this.cityOptions[i].city;
      }
    }
  },
  async mounted() {
    await this.getCardInfo();
  },
  watch: {
    "avatarPreviewList.length": function (newValue, oldValue) {
      this.isHideUploadEdit = newValue >= 2;
    },
  },
  computed: {
    submitAble() {
      return Object.keys(this.userInfo).every((key) => {
        if (key == "storeId" && this.isCustumShop) return true;
        if (key == "shopId" && this.isCustumShop) return true;
        if (this.userInfo.istg == "2" && this.userInfo.noPassReason && this.userInfo.noPassReasonKey) return true;
        return !!this.userInfo[key];
      });
    },
  },
  methods: {
    submitForm(userInfo) {
      this.$refs[userInfo].validate((valid) => {
        if (valid) {
          this.loadingBut=true
          let param = { ...this.userInfo };
          // 提交时还原标识符
          if (param.storeId == "-") param.storeId = "";
          if (param.shopId == "-") param.shopId = "";
          // type  1认证通过 3认证不通过
          userVerified(Object.assign({}, param, { type: this.userInfo.istg === "1" ? 1 : 3 })).then(({ data }) => {
            if (data.isSuccess) {
              this.$message({ type: "success", message: `操作成功！`, duration: 3000 });
              this.$router.back();
            } else {
              this.$message({ type: "error", message: data.errorMessage, duration: 3000 });
            }
            this.loadingBut=false
          });
        }
      });
    },
    remoteStoreHandler(query) {
      if (query !== "") {
        searchStore({
          storeName: query,
          page: 1,
          pageSize: 99,
        }).then(({ data }) => {
          if (data.isSuccess && data.content) {
            this.storeOptions = data.content.rows;
          }
        });
      } else {
        this.storeOptions = [];
      }
    },

    // 品牌
    remoteShopHandler(query) {
      if (query !== "") {
        searchShop({
          shopShortName: query,
          page: 1,
          pageSize: 99,
        }).then(({ data }) => {
          if (data.isSuccess && data.content) {
            this.shopOptions = data.content.rows;
          }
        });
      } else {
        this.shopOptions = [];
      }
    },

    handleChangeStore(e) {
      let item = this.storeOptions.find((v) => v.storeId == e);
      this.userInfo.storeName = item.storeName;
      this.userInfo.storeId = item.storeId;
      this.userInfo.storeAddr = item.storeAddr;
    },

    handleChangeShop(e) {
      let item = this.shopOptions.find((v) => v.shopId == e);
      this.userInfo.shopId = item.shopId;
      this.userInfo.shopShortName = item.shopShortName;
    },

    // 查询数据
    async getCardInfo() {
      this.loading = true;
      let userId = (this.userInfo.userId = this.$route.query.userId);
      let res = await onlineauthentication({ userId });
      if (res && res.data && res.data.content) {
        //认证来源
        this.userInfo.saleUserId = res.data.content.authSource.id;
        this.userInfo.authSource = res.data.content.authSource.agentId;
        this.authSourceName = res.data.content.authSource.userName;
        this.authSourceList = res.data.content.authSourceEnum;

        // 未通过原因
        this.selectValueTmp = res.data.content;
        this.selectValue = this.userInfo.noPassReasonKey = this.selectValueTmp.noPassReasonEnum[0].key;
        this.userInfo.noPassReason = this.selectValueTmp.noPassReasonEnum[0].value;
        this.setPassReason = this.selectValueTmp.noPassReasonEnum;

        if (res.data.content.userOnlineAuthenticationRespVO) {
          this.imgList = res.data.content.userOnlineAuthenticationRespVO.imgList;
          this.carInfoList = res.data.content.userOnlineAuthenticationRespVO.carInfoList;
          let time = res.data.content.userOnlineAuthenticationRespVO.authenticationTime.split(" ");
          this.authenticationTime = time[0];
          this.userInfo.mobile = res.data.content.mobile;
        }
        if (res.data.content.authenticationBossInfoVo) {
          let newAddFile = res.data.content.newAddFile;
          if (newAddFile) {
            for (let i in newAddFile) {
              this.avatarPreviewList.push({ name: "", url: newAddFile[i] });
            }
            this.userInfo.newAddFileId = res.data.content.newAddFileId;
          }
          if (res.data.content.mobile) {
            this.userInfo.mobile = res.data.content.mobile;
          }
          let infoTmp = res.data.content.authenticationBossInfoVo;
          this.userInfo.realName = infoTmp.realName;
          this.userInfo.city = infoTmp.city;
          // 品牌
          this.userInfo.shopId = infoTmp.shopId;
          this.userInfo.shopShortName = infoTmp.shopShortName;
          // 门店
          this.userInfo.storeId = infoTmp.storeId;
          this.userInfo.storeName = infoTmp.storeShortName;
          this.userInfo.storeAddr = infoTmp.storeAddr;

          // 审核结论
          if (res.data.content.isVerify) {
            this.isfailedAudit = false;
            this.userInfo.istg = "1";
            this.userInfo.noPassReason = " ";
            this.userInfo.noPassReasonKey = " ";
          } else {
            this.isfailedAudit = true;
            this.userInfo.istg = "2";
            if (this.authentType == 2) {
              this.selectValue = this.userInfo.noPassReasonKey = this.selectValueTmp.noPassReasonEnum[0].key;
              this.userInfo.noPassReason = this.selectValueTmp.noPassReasonEnum[0].value;
            } else {
              this.selectValue = this.userInfo.noPassReasonKey = this.selectValueTmp.noPassReasonKey;
              this.userInfo.noPassReason = this.selectValueTmp.noPassReason;
            }
          }
        }
        this.loading = false;
      }
    },

    cancel() {
      this.$router.back();
    },

    // 手工创建
    showPop() {
      this.createShopVisible = true;
    },
    handleCreateShop(e) {
      const { city, shopShortName, storeName, storeAddr } = e;
      const id = "-"; //标志符
      this.userInfo.city = city;
      this.userInfo.storeId = id;
      this.userInfo.storeName = storeName;
      this.userInfo.storeAddr = storeAddr;
      this.storeOptions = [{ storeAddr, storeId: id, storeName }];

      this.userInfo.shopId = id;
      this.userInfo.shopShortName = shopShortName;
      this.shopOptions = [{ shopId: id, shopShortName }];
    },

    //审核结论
    failedAudit(tmp) {
      if (tmp == "true") {
        this.isfailedAudit = false;
        this.userInfo.istg = "1";
        this.userInfo.noPassReason = " ";
        this.userInfo.noPassReasonKey = " ";
      }
      if (tmp == "false") {
        this.isfailedAudit = true;
        this.userInfo.istg = "2";
        if (this.authentType == 2 || this.authentType == 3) {
          this.selectValue = this.userInfo.noPassReasonKey = this.selectValueTmp.noPassReasonEnum[0].key;
          this.userInfo.noPassReason = this.selectValueTmp.noPassReasonEnum[0].value;
        } else {
          this.selectValue = this.userInfo.noPassReasonKey = this.selectValueTmp.noPassReasonKey;
          this.userInfo.noPassReason = this.selectValueTmp.noPassReason;
        }
      }
    },

    //更换名片图
    onUploadSuccess(res, file, fileList) {
      if (res && res.length) {
        this.userInfo.newAddFileId = this.userInfo.newAddFileId.concat(res[0].id);
      } else {
        this.$message.error("图片上传失败");
      }
      this.isHideUploadEdit = fileList.length >= 2;
    },
    onUploadError() {
      this.$message.error("图片上传失败");
    },
    onUploadExceed() {
      this.$message.error("最多只能上传两张名片图");
    },
    onUploadBefore(file) {
      let isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
      if (!isJPG) {
        this.$message.error("上传图片只能是 image/jpeg/png 格式!");
      }
      return isJPG;
    },
    onUploadRemove(file, fileList) {
      this.userInfo.newAddFileId = [];
      this.isHideUploadEdit = fileList.length >= 2;
    },
    // 取消认证
    cancelBut() {
      this.$confirm(`确定取消${this.userInfo.realName || "无名"}的用户认证`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        userVerified({
          type: 2,
          userId: this.$route.query.userId,
        }).then(({ code }) => {
          if (code == 200) {
            this.$message({ type: "success", message: `取消认证成功！`, duration: 3000 });
            this.$router.back();
          } else {
            this.$message({ type: "error", message: `操作失败！`, duration: 3000 });
          }
        });
      });
    },
    // 保存并更新
    saveConfirm(userInfo) {
      this.submitForm(userInfo);
    },

    //点击图片
    bindImg(tmp) {
      if (tmp) {
        this.fontImg = !this.fontImg;
      } else {
        this.fontImg = !this.fontImg;
      }
    },

    //下拉选择项值改变触发
    handleChangeSelectValue(e) {
      this.userInfo.noPassReasonKey = e;
      for (let k in this.setPassReason) {
        if (this.setPassReason[k].key === e) {
          this.userInfo.noPassReason = this.setPassReason[k].value;
        }
      }
    },
    handleChangeAuthSource(e) {
      for (let k in this.authSourceList) {
        if (this.authSourceList[k].userName === e) {
          this.userInfo.saleUserId = this.authSourceList[k].id;
          this.userInfo.authSource = this.authSourceList[k].agentId;
        }
      }
    },
  },
};
</script>
<style scoped>
.app-container {
  margin: 20px;
  border: 1px solid #ccc;
}
.cardInfo {
  border-bottom: 1px solid #ccc;
  padding-bottom: 20px;
}
.cardImg {
  margin: 0 20px 10px 0;
  width: 250px;
  height: 200px;
  border: 1px solid #ccc;
}
.cardImgx {
  margin: 0 20px 10px 0;
  width: 550px;
  height: 500px;
  border: 1px solid #ccc;
}
.dis {
  display: flex;
  margin-top: 20px;
}
.cardInfoItem {
  max-height: 450px;
  overflow: auto;
  margin-right: 30px;
}
.info {
  display: flex;
}
.mpImg {
  width: 100%;
  height: 100%;
}
</style>>

<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>